package sicnu.cs.ich.security.domain.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/10/24-20:06
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Permission implements Serializable, GrantedAuthority,Comparable<Permission> {
    private Integer id;
    @JsonIgnore
    private Boolean available;

    private String permission;

    private Integer parentId;
    @JsonIgnore
    private String parentIds;

    private String description;

    private Integer level;
    private boolean menu;
    private volatile List<Permission> children;

    public void addChild(Permission child) {
        if (children == null) {
            synchronized (this) {
                // 双重校验
                if (children == null) {
                    children = new ArrayList<>();
                }
            }
        }
        children.add(child);
    }

    @Override
    public String getAuthority() {
        return permission;
    }

    @Override
    public int compareTo(Permission o) {
        if(o==null) return -1;
        else return this.getLevel()- o.getLevel();
    }
}
